import path from "path";
import * as fs from "fs-extra";
import { loadConfigFromFile } from "vite";
import { readdir, statSync } from "fs-extra";
import consola from "consola";

/**
 * 加载配置文件内容
 *
 * @export
 * @template T
 * @param {string} pathStr
 * @param {string[]} files
 * @return {*}  {Promise<T>}
 */
export async function loadConfigFile<T = any>(
  pathStr: string,
  files: string[]
): Promise<T> {
  // 配置文件路径
  let configPath: string | undefined;
  if (pathStr) {
    configPath = path.resolve(pathStr);
  } else {
    // 查找预置的配置文件类型
    for (const filename of files) {
      const filePath = path.resolve(process.cwd(), filename);
      if (!fs.existsSync(filePath)) {
        continue;
      }
      configPath = filePath;
      break;
    }
  }
  if (!configPath) {
    throw new Error(`未找到配置文件，请检查 ${files.join(" 或 ")} 是否存在`);
  }
  // 利用 vite 的配置文件解析方法，解析配置文件
  const result = await loadConfigFromFile(
    { command: "build", mode: "development" },
    configPath
  );
  if (!result) {
    throw new Error("配置文件解析失败");
  }
  // 从解析结果中获取配置
  return result.config as any;
}

/**
 * 获取指定路径下子数据
 *
 * @export
 * @param {string} strPath 指定路径
 * @param {boolean} isFile 文件or目录
 */
export async function getChildByPath(
  strPath: string,
  isFile: boolean
): Promise<string[]> {
  const targetChild: string[] = [];
  try {
    const files = await readdir(strPath);
    files.forEach((file: string) => {
      const pathname = path.join(strPath, file);
      if (statSync(pathname).isDirectory()) {
        if (!isFile) {
          targetChild.push(pathname);
        }
      } else {
        if (isFile) {
          targetChild.push(pathname);
        }
      }
    });
  } catch (error) {
    consola.error(`获取指定路径下子数据执行异常,${JSON.stringify(error)}`);
  }
  return targetChild;
}
